﻿using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;

namespace Orktane.Samples.ConsoleAppWeb.Services
{
    public class RemoteProcessesService 
        : IRemoteProcessesService
    {

#region IRemoteProcessesService Memebers

        public RemoteProcess[] GetRunningProcesses(string namePattern)
        {
            var _regex = (Regex)null;
            if (!string.IsNullOrEmpty(namePattern)) _regex = new Regex(Regex.Escape(namePattern), RegexOptions.IgnoreCase | RegexOptions.ECMAScript);

            return Process.GetProcesses().Select((p) => new RemoteProcess()
            {
                ProcessId = p.Id,
                ProcessName = string.IsNullOrEmpty(p.MainWindowTitle) ? p.ProcessName : p.MainWindowTitle,
                WorkingMemorySize = p.WorkingSet64
            })
            .Where((p) => _regex != null ? _regex.IsMatch(p.ProcessName) : true)
            .OrderByDescending((p) => p.WorkingMemorySize).ToArray();
        }

        public bool StopProcess(int processId)
        {   
            Process _process = Process.GetProcessById(processId);
            if (_process != null)
            {
                _process.Kill();                    
                return true;
            }
            return false;
        }

        public RemoteProcess StartProcess(string fileName)
        {
            Process _process = Process.Start(fileName);
            if (_process != null)
            {
                return new RemoteProcess()
                {
                    ProcessId = _process.Id,
                    ProcessName = string.IsNullOrEmpty(_process.MainWindowTitle) ? _process.ProcessName : _process.MainWindowTitle,
                    WorkingMemorySize = _process.WorkingSet64
                };
            }
            else 
            {
                return null;
            }
        }

#endregion

    }
}
